let storage = bui.storage();
let org;
let language
let translate
let zxEditor
let uploadPicUrl;
loader.define(function (require, exports, module, global) {
    let pageview = {
        init() {
            uploadPicUrl = global.api.imageAnalysisForUEditorArticle
            translate = global.translate
            language = storage.get("language", 0)
            if (!language) {
                language = 'chinese_simplified'
            }

            try {
                translate.selectLanguageTag.show = false;
                let curLanguage = translate.language.getCurrent()
                if (curLanguage !== language) {
                    translate.changeLanguage(language)
                }
                translate.execute();
            }catch (e) {
                console.log("切换语言报错")
            }
            if (language === "chinese_simplified") {
                router.$("#J_Form").css("font-size", "")
                router.$(".bui-input").css("font-size", "")
                router.$("#nameFb").css("font-size", "")
            } else {
                router.$("#J_Form").css("font-size", ".22rem")
                router.$(".bui-input").css("font-size", ".22rem")
                router.$("#nameFb").css("font-size", ".3rem")
            }

            let uiLoading = bui.loading({
                appendTo:"#fbLoading",
                width: 40,
                height: 40,
                opacity: 0.5,
                text:"加载中。。。",
                autoClose: false
            });
            let uiLoadingBtn = bui.loading({
                appendTo:"#fbLoading",
                width: 40,
                height: 40,
                opacity: 0.5,
                text:"提交中。。。",
                autoClose: false
            });

            router.$("#fbFh").click(function () {
                // router.load({ url: "pages/fbZj/fbZj.html"});
                let prevInfo = bui.history.getCurrentPrev()
                router.replace({url: prevInfo.url});
            })

            let token = storage.get("token",0)
            org = storage.get("org",0)
            let cateDo = storage.get("cateDo",0)
            if (org != null) {
                router.$("#nameFb").html("发布" +org.description + "信息")
            }
            if (token) {
                uiLoading.show()
                bui.ajax({
                    url: global.api.verifyToken,
                    method: "POST",
                    headers: {Token: token}
                }).then(function(res) {
                    if (res.code != '200') {
                        bui.confirm({
                            "title": "",
                            "height": 460,
                            "content": '<div class="bui-box-center"><div><h3>登录已过期</h3></div></div>',
                            "buttons": [{ name: "确定", className: "primary-reverse" }],
                            callback:function(){
                                this.close();
                                storage.set("tzPage", 0)
                                router.replace({ url: "pages/mainIndex/mainIndex.html"});
                            }
                        });
                    } else {
                        let user = res.data
                        let contentStatus = false, emailStatus = true, refreshcountStatus = true, titleStatus = true,linkStatus = false, addressStatus = false, concatStatus = false, telStatus = false

                        let imgStr = '';
                        let fixDateStr = ''
                        let fixDateStrZj = ''
                        let fix1DateStr = ''
                        let fix1DateStrZj = ''
                        let refreshtimeStr = ''
                        let refreshtimeStrZj = ''
                        let refreshcountZj = ''
                        let webSign = ''
                        let serverIds = []

                        if (user.userId != 1 && (!user.adminType || user.adminType == '1')) {
                            router.$('.glyqx').hide()
                            router.$('.glyqx1').hide()
                            router.$('.glyqx2').hide()

                            if (user.qxStr) {
                                if (user.qxStr.indexOf("2") > -1){
                                    router.$('.glyqx').show()
                                }
                                if (user.qxStr.indexOf("3") > -1){
                                    router.$('.glyqx1').show()
                                }
                                if (user.qxStr.indexOf("4") > -1){
                                    router.$('.glyqx2').show()
                                }
                            }
                        } else {
                            router.$('.glyqx').show()
                            router.$('.glyqx1').show()
                            router.$('.glyqx2').show()
                        }

                        // 企业名称
                        let title = bui.input({
                            id: "#titleInput",
                            showIcon: false,
                            onInput: function(e) {
                                if (e.target.value) {
                                    if (e.target.value.length > 100) {
                                        titleStatus = false
                                        router.$("#titleTs").html("企业名称最多100个字")
                                        return false;
                                    } else {
                                        titleStatus = true
                                        router.$("#titleTs").html("")
                                    }
                                } else {
                                    titleStatus = false
                                    router.$("#titleTs").html("企业名称不可为空")
                                    return false;
                                }
                                return true;
                            }
                        })
                        //企业地址
                        let address = bui.input({
                            id: "#addressInput",
                            showIcon: false,
                            onInput: function(e) {
                                if (e.target.value) {
                                    if (e.target.value.length > 255) {
                                        addressStatus = false
                                        router.$("#addressTs").html("企业地址最多255个字")
                                        return false;
                                    } else {
                                        addressStatus = true
                                        router.$("#addressTs").html("")
                                    }
                                } else {
                                    addressStatus = false
                                    router.$("#addressTs").html("企业地址不可为空")
                                    return false;
                                }
                                return true;
                            }
                        })
                        //联系人
                        let concat = bui.input({
                            id: "#concatInput",
                            showIcon: false,
                            onInput: function(e) {
                                if (e.target.value) {
                                    if (e.target.value.length > 50) {
                                        concatStatus = false
                                        router.$("#concatTs").html("联系人最多50个字")
                                        return false;
                                    } else {
                                        concatStatus = true
                                        router.$("#concatTs").html("")
                                    }
                                } else {
                                    concatStatus = false
                                    router.$("#concatTs").html("联系人不可为空")
                                    return false;
                                }
                                return true;
                            }
                        })
                        //联系方式
                        let tel = bui.input({
                            id: "#telInput",
                            showIcon: false,
                            onInput: function(e) {
                                if (e.target.value) {
                                    if (e.target.value.length > 25) {
                                        telStatus = false
                                        router.$("#telTs").html("联系方式最多25个字")
                                        return false;
                                    } else {
                                        telStatus = true
                                        router.$("#telTs").html("")
                                    }
                                } else {
                                    telStatus = false
                                    router.$("#telTs").html("联系方式不可为空")
                                    return false;
                                }
                                return true;
                            }
                        })
                        let email = bui.input({
                            id: "#emailInput2",
                            showIcon: false,
                            onInput: function(e) {
                                let rule = /^([a-zA-Z\d][\w-]{2,})@(\w{2,})\.([a-z]{2,})(\.[a-z]{2,})?$/
                                if (e.target.value) {
                                    if (!rule.test(e.target.value)) {
                                        emailStatus = false
                                        router.$("#emailTs2").html("邮箱格式不对")
                                        return false;
                                    } else {
                                        emailStatus = true
                                        router.$("#emailTs2").html("")
                                    }
                                } else {
                                    emailStatus = true
                                    router.$("#emailTs2").html("")
                                    return false;
                                }
                                return true;
                            }
                        })


                        // 初始化ZX编辑器
                        zxEditor = new ZxEditor('#editor', {
                            disableBackspaceDelete: false,
                            imageMaxSize: 5,
                            customPictureHandler:false,    //自定义图片处理，即不使用默认插入图片逻辑。
                            showToolbar: ['pic','text', 'link']
                        })
                        if (isWeiXin()) {
                            webSign = '1'
                            //获取微信配置
                            bui.ajax({
                                url: global.api.getWxConfig,
                                data: {url: location.href.split('#')[0]},
                                method: "GET"
                            }).then(function(res) {
                                if (res.code == '200') {
                                    let dat = res.data

                                    wx.config({
                                        debug: false,
                                        appId: dat.appId,
                                        timestamp: dat.timestamp,
                                        nonceStr: dat.nonceStr,
                                        signature: dat.signature,
                                        jsApiList: [
                                            // 所有要调用的 API 都要加到这个列表中
                                            'checkJsApi','chooseImage', 'previewImage', 'uploadImage', 'downloadImage','onMenuShareTimeline','chooseWXPay','getLocalImgData'
                                        ]
                                    })
                                    wx.ready(function () {
                                        // 自定义选择图片
                                        zxEditor.on('select-picture', next => {
                                            wx.chooseImage({//选择图片
                                                count: 9,//限制上传图片的张数
                                                success: function (res) {
                                                    let localIds = res.localIds;
                                                    if (localIds.length > 0) {
                                                        uiLoading.show()
                                                        photoUpload(localIds);
                                                    } else {
                                                        bui.alert("未选择上传图片")
                                                    }

                                                    function photoUpload(localIds){//照片上传
                                                        let localId = localIds.splice(0, 1)[0];
                                                        //ios专用
                                                        if(localId.indexOf("wxlocalresource") != -1){
                                                            localId = localId.replace("wxlocalresource", "wxLocalResource");
                                                        }
                                                        //当不使用定时器的时候，连续上传1+照片后，会莫明其妙滴不再执行，迫不得已掏出定时器这个大杀器~
                                                        setTimeout(function(){
                                                            wx.uploadImage({//上传图片
                                                                localId: localId,
                                                                isShowProgressTips: 0,
                                                                success: function (res) {
                                                                    let serverId = res.serverId
                                                                    picShow(localId, serverId)
                                                                    if(localIds.length >= 1){
                                                                        photoUpload(localIds);
                                                                    }
                                                                    if (localIds.length == 0) {
                                                                        uiLoading.stop()
                                                                    }
                                                                }
                                                            })
                                                        },50);
                                                    }

                                                    function picShow(data, serverId) {
                                                        zxEditor.addImage(data, serverId);
                                                    }
                                                }
                                            })
                                        })
                                    })
                                }
                            })
                        } else {
                            let $fileInput = initFileInput()
                            // 自定义选择图片
                            zxEditor.on('select-picture', next => {
                                $fileInput.click();
                            })
                        }
                        //拖拽图片上传
                        zxEditor.addEvent(zxEditor.$content, 'drop', e=>{
                            e.preventDefault()
                            e.stopPropagation()
                            const items = e.dataTransfer.items;
                            for (let i = 0; i < items.length; i++) {
                                let item = items[i]
                                if ('text/html' === item.type) {
                                    item.getAsString(str => {
                                        zxEditor.dialog.loading("加载中")
                                        disposePasteImg(str, global.api.imageAnalysisArticle).then((res) => {
                                            let srcReg2 = /src=[\'\"]?([^\'\"]*)[\'\"]?/i
                                            let img_src = res.match(srcReg2)[1];
                                            //正则把?x-oss-process后面的都去掉
                                            if (img_src) {
                                                img_src = img_src.replace(/\?.*/i, "");
                                                zxEditor.addImage(img_src)
                                            }
                                            zxEditor.dialog.removeLoading()
                                        });
                                    })
                                }
                            }
                        })
                        zxEditor.addEvent(zxEditor.$content, 'paste', function (e) {
                            e.preventDefault();
                            let clipboardData = e.clipboardData
                            if (!clipboardData) return
                            let items = clipboardData.items
                            // console.log(e)
                            // console.log(clipboardData.getData("text"))
                            if (items) {
                                let len = items.length
                                let i, item;
                                for (i = 0; i < len; i++) {
                                    item = items[i]
                                    if (item.type === 'text/html') {
                                        item.getAsString(str => {
                                            if (str) {
                                                zxEditor.dialog.loading("加载中")
                                                let newStr = str
                                                if (str.indexOf("<!--StartFragment-->") > -1) {
                                                    newStr = str.split('<!--StartFragment-->') [1].split('<!--EndFragment-->')[0]
                                                }
                                                disposePasteImg(newStr, global.api.imageAnalysisArticle).then((res) => {
                                                    $(zxEditor.$content).append(res)
                                                    zxEditor.dialog.removeLoading()
                                                });
                                            }
                                        })
                                    } else if (item.type === 'text/plain' && len === 1) {
                                        item.getAsString(str => {
                                            _insertToContent(str);
                                        })
                                    }
                                }
                            }
                        });
                        // 编辑器内容改变
                        zxEditor.on('change', function (type, zxeditor) {
                            let content = zxeditor.getContent()
                            if (content !== '<p><br></p>') {
                                contentStatus = true
                                router.$("#contentTs").html('')
                            } else {
                                contentStatus = false
                                router.$("#contentTs").html('内容不可为空')
                            }
                        })
                        zxEditor.on('add-link', next => {
                            router.$("#linkTitle").val('')
                            router.$("#link").val('')
                            linkStatus = false
                            alterLinkDialog.open()
                        })
                        // 链接
                        let link = bui.input({
                            id: "#linkInput",
                            showIcon: false,
                            onInput: function(e) {
                                let rule = /^(https:\/\/?|HTTPS:\/\/?|http:\/\/?|HTTP:\/\/)[A-Za-z0-9.\/_\-]+$/
                                if (e.target.value) {
                                    if (!rule.test(e.target.value)) {
                                        linkStatus = false
                                        router.$("#linkTs").html("链接必须以(http(s))开头")
                                        return false;
                                    } else {
                                        linkStatus = true
                                        router.$("#linkTs").html("")
                                    }
                                } else {
                                    linkStatus = false
                                    router.$("#linkTs").html("链接不可为空")
                                    return false;
                                }

                                return true;
                            }
                        })
                        // 自定义居中弹出框
                        let alterLinkDialog = bui.dialog({
                            id: "#alterLinkDialog",
                            height: 300,
                            // mask: false,
                            callback: function(e) {
                                let cla = router.$(e.target).attr('class')
                                if (cla.indexOf('blue') > -1) {
                                    if (linkStatus) {
                                        zxEditor.addLink(link.value(), router.$("#linkTitle").val())
                                        this.close();
                                    } else {
                                        bui.confirm({
                                            "title": "",
                                            "height": 460,
                                            "content": '<div class="bui-box-center"><div><h3>链接为空，或者不符合规则</h3></div></div>',
                                            "buttons": [{ name: "确定", className: "primary-reverse" }],
                                            callback:function(){
                                                this.close();
                                            }
                                        });
                                    }
                                }
                            }
                        });

                        let refreshcount = bui.input({
                            id: "#refreshcountInput2",
                            showIcon: false,
                            onInput: function(e) {
                                let rule = /^\d{0,10}?$/
                                if (e.target.value) {
                                    if (!rule.test(e.target.value)) {
                                        refreshcountStatus = false
                                        router.$("#refreshcountTs2").html("剩余刷新次数只能是整数最大99999999999次")
                                        return false;
                                    } else {
                                        refreshcountStatus = true
                                        router.$("#refreshcountTs2").html("")
                                    }
                                } else {
                                    refreshcountStatus = true
                                    router.$("#refreshcountTs2").html("")
                                    return false;
                                }
                                return true;
                            }
                        })

                        let fix = bui.pickerdate({
                            handle: "#datepicker_input_fix2",
                            bindValue: true, // 1.5.3 新增, 修改的值会自动绑定到 handle, 不再需要自己去绑定
                            // input 显示的日期格式
                            formatValue: "yyyy-MM-dd hh:mm:ss",
                            callback: function(e) {
                                fixDateStr = this.value()
                            }
                            // 如果不需要按钮,设置为空
                            // buttons: [{name:"取消"}]
                        });
                        fix.empty()
                        let fix1 = bui.pickerdate({
                            handle: "#datepicker_input_fix12",
                            bindValue: true, // 1.5.3 新增, 修改的值会自动绑定到 handle, 不再需要自己去绑定
                            // input 显示的日期格式
                            formatValue: "yyyy-MM-dd hh:mm:ss",
                            callback: function(e) {
                                fix1DateStr = this.value()
                            }
                            // 如果不需要按钮,设置为空
                            // buttons: [{name:"取消"}]
                        });
                        fix1.empty()
                        let refreshtime = bui.pickerdate({
                            handle: "#datepicker_input_refreshtime2",
                            bindValue: true, // 1.5.3 新增, 修改的值会自动绑定到 handle, 不再需要自己去绑定
                            // input 显示的日期格式
                            formatValue: "hh:mm:ss",
                            callback: function(e) {
                                refreshtimeStr = this.value()
                            }
                            // 如果不需要按钮,设置为空
                            // buttons: [{name:"取消"}]
                        });
                        refreshtime.cols({
                            year: "none",
                            month: "none",
                            date: "none",
                        })
                        refreshtime.empty()

                        router.$("input[name='isFix']").change(function () {
                            if (router.$(this).val() == '1') {
                                if (fixDateStrZj) {
                                    fixDateStr = fixDateStrZj
                                }
                                router.$("#fixDateK2").show()
                            } else {
                                fixDateStrZj = fixDateStr
                                fixDateStr = ""
                                router.$("#fixDateK2").hide()
                            }
                        })
                        router.$("input[name='isFix1']").change(function () {
                            if (router.$(this).val() == '1') {
                                if (fix1DateStrZj) {
                                    fix1DateStr = fix1DateStrZj
                                }
                                router.$("#fix1DateK2").show()
                            } else {
                                fix1DateStrZj = fix1DateStr
                                fix1DateStr = ""
                                router.$("#fix1DateK2").hide()
                            }
                        })
                        router.$("input[name='refresh']").change(function () {
                            if (router.$(this).val() == '1') {
                                if (refreshtimeStrZj) {
                                    refreshtimeStr = refreshtimeStrZj
                                }
                                if (refreshcountZj) {
                                    router.$("#refreshcount2").val(refreshcountZj)
                                }
                                router.$(".refreshK").show()
                            } else {
                                refreshtimeStrZj = refreshtimeStr
                                refreshcountZj = router.$("#refreshcount2").val()
                                refreshtimeStr = ""
                                router.$("#refreshcount2").val("")
                                router.$(".refreshK").hide()
                            }
                        })


                        // 拍照上传
                        let $facePhoto = router.$("#buiPhotoAd");
                        let $uploadBtn = router.$("#picK");
                        let uiUpload = bui.upload({
                            showProgress: true,
                            // needNative: false
                        });
                        // 上拉菜单 js 初始化:
                        bui.actionsheet({
                            trigger: "#btnUploadAd",
                            buttons: [{ name: "拍照上传", value: "camera" }, { name: "从相册选取", value: "photo" }],
                            callback: function(e) {
                                let ui = this;
                                let val = router.$(e.target).attr("value");
                                switch (val) {
                                    case "camera":
                                        ui.hide();
                                        uiUpload.add({
                                            "from": "camera",
                                            // "needCompress": true, // 1.5.3新增压缩
                                            // "width": 300,
                                            "destinationType": "file", //  file | blob | data
                                            "onSuccess": function(val, data) {
                                                // 直接调用start上传图片
                                                this.start({
                                                    url: global.api.pzPicUpload,
                                                    data: {
                                                        file: this.data().file
                                                    },
                                                    onSuccess: function(data) {
                                                        // bui.alert(data);
                                                        if (data.code == '200') {
                                                            router.$('#btnUploadAd').hide()
                                                            $uploadBtn.show()
                                                            imgStr = data.data.image
                                                            $uploadBtn.html(templatePhoto(global.api.baseurl + "profile/58Upload/pz/" + data.data.image, uiUpload))
                                                        } else {
                                                            bui.alert(data.msg)
                                                        }
                                                    },
                                                    onFail: function(data) {
                                                        bui.alert("图片上传失败！")
                                                    },
                                                })
                                            }
                                        })
                                        break;
                                    case "photo":
                                        ui.hide();
                                        uiUpload.add({
                                            "from": "",
                                            "onSuccess": function(val, data) {
                                                this.start({
                                                    url: global.api.pzPicUpload,
                                                    data: {
                                                        file: this.data().file
                                                    },
                                                    onSuccess: function(data) {
                                                        // bui.alert(data);
                                                        if (data.code == '200') {
                                                            router.$('#btnUploadAd').hide()
                                                            imgStr = data.data.image
                                                            $uploadBtn.html(templatePhoto(global.api.baseurl + "profile/58Upload/pz/" + data.data.image, uiUpload))
                                                            $uploadBtn.show()
                                                        } else {
                                                            bui.alert(data.msg)
                                                        }
                                                    },
                                                    onFail: function(data) {
                                                        bui.alert("图片上传失败！")
                                                    },
                                                })
                                            }
                                        })
                                        break;
                                    case "cancel":
                                        ui.hide();
                                        break;
                                }
                            }
                        })
                        // 选择图片文件
                        $facePhoto.on("click", ".icon-removefill", function(e) {
                            var $item = router.$(this).parents(".span1");
                            var name = $item.attr("data-name");

                            // 删除对应的上传数据
                            uiUpload.remove(name);
                            // 删除dom显示
                            // $item.remove();
                            $item.empty();
                            // $("#picK").empty()
                            e.stopPropagation();

                            imgStr = ""
                            router.$('#btnUploadAd').show()
                            $uploadBtn.hide()
                        })

                        router.$("#fbArticle").click(function () {
                            let context = zxEditor.getContent(true).trim()
                            if (contentStatus && emailStatus && refreshcountStatus && titleStatus && addressStatus && telStatus && concatStatus) {
                                uiLoadingBtn.show()
                                bui.ajax({
                                    url: global.api.insertArticle,
                                    data: {title: title.value(), contentText: context,content: zxEditor.getContent(), cityId: org.id, city: org.name, country: org.pName, isreview: org.isreview, isduplicate: org.isduplicate,validSign: cateDo.validSign,
                                        cate: cateDo.id, cate2: cateDo.parent, email: email.value(), wx: router.$("#wx").val(), tel: tel.value(),isfix: router.$("input[name='isFix']:checked").val(),
                                        isfix1: router.$("input[name='isFix1']:checked").val(), refresh: router.$("input[name='refresh']:checked").val(),fixexpStr: fixDateStr, fixexpStr1: fix1DateStr,refreshtimeStr: refreshtimeStr,
                                        refreshcount: refreshcount.value(), webSign: webSign, zizhiPic: imgStr, adress: address.value(), concat: concat.value()},
                                    method: "POST",
                                    headers: {Token: token}
                                }).then(function(res){
                                    if (res.code == '200') {
                                        if(res.mSign == '0') {
                                            // 修改数据
                                            bui.confirm("发布成功，请在主页查看！", function(e) {
                                                //this 是指点击的按钮
                                                let text = router.$(e.target).text();

                                                if (text == "确定") {
                                                    storage.set("tzPage", 0)
                                                    router.replace({ url: "pages/mainIndex/mainIndex.html"});
                                                }
                                                this.close()
                                            });
                                        } else {
                                            bui.confirm({
                                                "title": "",
                                                "height": 460,
                                                "content": '<div class="bui-box-center"><div><img src="'+res.qrcode+'" width="70px" height="70px"><p>发布成功，可扫码联系管理员审核！</p></div></div>',
                                                "buttons": ["取消","确定"],
                                                callback: function(e) {
                                                    //this 是指点击的按钮
                                                    let text = router.$(e.target).text();

                                                    if (text == "确定") {
                                                        storage.set("tzPage", 0)
                                                        router.replace({ url: "pages/mainIndex/mainIndex.html"});
                                                    }
                                                    this.close()
                                                }
                                            });
                                        }
                                    } else {
                                        bui.alert("发布失败！")
                                    }
                                    uiLoadingBtn.stop()
                                })
                            } else {
                                if (!contentStatus) {
                                    router.$("#contentTs").html('内容不可为空')
                                }
                                if (!titleStatus) {
                                    router.$("#titleTs").html('企业名称不可为空')
                                }
                                if (!addressStatus) {
                                    router.$("#titleTs").html('企业地址不可为空')
                                }
                                if (!telStatus) {
                                    router.$("#telTs").html('联系方式不可为空')
                                }
                                if (!concatStatus) {
                                    router.$("#concatTs").html('联系人不可为空')
                                }

                                bui.alert("数据不符合格式，请检查！")
                            }
                        })
                    }
                    uiLoading.stop()
                });
            } else {
                bui.confirm({
                    "title": "",
                    "height": 460,
                    "content": '<div class="bui-box-center"><div><h3>当前未登录，请登录</h3></div></div>',
                    "buttons": [{ name: "登录", className: "primary-reverse" }],
                    callback:function(){
                        this.close();
                        storage.set("tzPage", 0)
                        router.replace({ url: "pages/mainIndex/mainIndex.html"});
                    }
                });
            }

            try {
                translate.execute();
            }catch (e) {
                console.log("切换语言报错")
            }
        }
    };

    // 初始化
    pageview.init();

    // 输出模块
    return pageview;
})

function isWeiXin() {
    let ua = navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true
    } else {
        return false
    }
}

function isMobile() {
    let info = navigator.userAgent;
    //通过正则表达式的test方法判断是否包含“Mobile”字符串
    let isPhone = /mobile/i.test(info);
    //如果包含“Mobile”（是手机设备）则返回true
    return isPhone;
}

// 处理粘贴的图片，传递的参数是粘贴来的数据
function disposePasteImg(pasteStr, url) {
    return new Promise(function (resolve) {
        // 用于计数图片数量
        let imgNum = 0;
        //匹配图片
        let imgReg = /<img.*?(?:>|\/>)/gi;
        let imgReg2 = /<img.*?(?:>|\/>)/;
        //匹配src属性
        let srcReg = new RegExp(/src=[\'\"]?([^\'\"]*)[\'\"]?/i,"g");
        let srcReg2 = /src=[\'\"]?([^\'\"]*)[\'\"]?/i

        if (imgReg2.test(pasteStr)) {
            // 提取图片连接
            pasteStr.replace(imgReg, function (txt) {
                console.log("txt：")
                console.log(txt)
                return txt.replace(srcReg, function (src) {
                    let img_src = src.match(srcReg2)[1];
                    //正则把?x-oss-process后面的都去掉
                    img_src = img_src.replace(/\?.*/i, "");
                    // 查找到一个图片地址就讲图片数量加1
                    imgNum++;

                    // console.log("img_src:", img_src)
                    if (img_src.indexOf('http:') > -1 || img_src.indexOf('https:') > -1) {
                        if (img_src.indexOf("/58Upload/article/") === -1) {
                            // 将图片转成图片文件对象并上传得到图片地址，传递的参数是图片地址
                            imgUrlSwitchBlob(img_src, url).then((res) => {
                                // console.log("得到的地址res", res);

                                /**
                                 * 得到图片地址进行替换并将替换之后的文本返回渲染
                                 */
                                // 图片地址进行替换
                                pasteStr = pasteStr.replace(img_src, res);
                                // 替换之后将图片数量减1
                                imgNum--;
                                // 只有图片数量变成0的时候才会进行返回
                                if (imgNum === 0) {
                                    // console.log("返回imgNum", imgNum,pasteStr)
                                    resolve(pasteStr);
                                }
                            });
                        } else {
                            imgNum--;
                            if (imgNum === 0) {
                                // console.log("返回imgNum", imgNum,pasteStr)
                                resolve(pasteStr);
                            }
                        }
                    }
                });
            });
        } else {
            resolve(pasteStr);
        }
    })
}

/**
 * @函数名称: 将图片地址转成文件对象
 * @返回值:图片地址
 * @描述: 接受的参数是图片的全地址路径，在函数中调用upPasteImg函数上传图片得到图片路径并返回
 * @其它: 使用Promise处理异步问题
 * @param {String} param 图片地址
 */
function imgUrlSwitchBlob(param, url) {
    console.log("图片参数：")
    console.log(param)
    return new Promise(function (resolve) {
        /**
         * @函数名称: 调用函数进行上传
         * @返回值: 得到的图片路径
         * @param {String} key 图片名称，包含后缀
         * @param {Object} blob 文件对象
         */
        bui.ajax({
            url: url,
            data: {fileUrl: param},
            method: "POST",
        }).then(function(res){
            if (res.code == '200') {
                resolve(res.data.image);
            } else {
                resolve('');
            }
        })
    });
}

/**
 * 初始化图片选择input[type=file]
 * @returns {*}
 */
function initFileInput() {
    let $input = zxEditor.createVdom({
        tag: 'input',
        attrs: {
            style: 'display: none',
            type: 'file',
            accept: 'image/*',
            multiple: 'multiple'
        }
    }); // 添加至文档流中

    zxEditor.$wrapper.appendChild($input); // 绑定change事件

    zxEditor.addEvent($input, 'change', fileInputChangeHandler); // 清除value，防止选中同一文件不触发change事件
    zxEditor.addEvent($input, 'click', function (e) {
        e.target.value = '';
    }); // 返回$input，模拟click[type=file]时使用
    return $input;
}
/**
 * input[file]选中文件后处理函数
 * @param e
 */
function fileInputChangeHandler(e) {
    let files = this.files; // 转数组
    let arr = zxEditor.slice(files);

    let all = arr.length
    let cur = 0
    if (all > 0) {
        zxEditor.dialog.loading("加载中")
        arr.forEach(file => {
            // 创建一个FileReader对象
            let reader = new FileReader();
            // 将图片文件读取为Data URL
            reader.readAsDataURL(file);
            // 监听文件加载完成事件
            reader.onload = function () {
                // 在这里进行下一步操作
                // 获取读取的图片文件的Data URL
                let dataURL = reader.result;
                // 将Data URL转换为base64字符串
                let base64String = "data:"+file.type+";base64," + dataURL.split(",")[1];
                uploadPic(base64String, file.type, file.size).then(res => {
                    cur++
                    if (cur >= all) {
                        zxEditor.dialog.removeLoading()
                    }
                })
            };
        })
    }
}
//上传图片
function uploadPic(base64, type, size) {
    return new Promise(function (resolve) {
        /**
         * @函数名称: 调用函数进行上传
         * @返回值: 得到的图片路径
         * @param {String} key 图片名称，包含后缀
         * @param {Object} blob 文件对象
         */
        bui.ajax({
            url: uploadPicUrl,
            data: {upfile: base64, type: type, size: size},
            method: "POST",
        }).then(function(res){
            if (res.state == 'SUCCESS') {
                zxEditor.addImage(res.url);
            }
            resolve('')
        })
    });
}

function _insertToContent(pasteStr) {
    if (!pasteStr) {
        zxEditor.dialog.alert('剪贴板无有效的文本内容');
    } else {
        // 去除html标签
        pasteStr = zxEditor.removeHtmlTags(pasteStr); // 创建文本节点

        let $paste = zxEditor.createVdom(pasteStr);

        zxEditor.insertElm($paste, 'text');

        let tmr = setTimeout(function (_) {
            zxEditor.checkCursorPosition();

            clearTimeout(tmr);
            tmr = null;
        }, 350);
    }
}

function templatePhoto(url, uiUpload) {
    return `<div class="span1" data-index="${uiUpload.currentIndex()}" data-name="${uiUpload.currentName()}">
                <div class="bui-upload-thumbnail"><img src="${url}" alt="" style="width: 2rem; height: 1.4rem"/><i class="icon-removefill"></i></div>
            </div>`
}
function templatePhotoDefault(url) {

    return `<div class="span1" data-index="-1" data-name="default.jpg">
                <div class="bui-upload-thumbnail"><img src="${url}" alt="" style="width: 2rem; height: 1.4rem"/><i class="icon-removefill"></i></div>
            </div>`
}

